﻿using System;
using System.IO;
using System.Text;
using System.Web.UI;
using TA.Turbo.Controls;
using System.Threading;
namespace TA.Turbo
{
	/// <summary>
	/// Describes a Turbo Page. Required for Turbo controls to work properly.
	/// </summary>
	public partial class TPage : System.Web.UI.Page, IEventHandler, IHasControlState
	{
		#region STATIC
		#region METHODS
#if DEBUG
		static StringBuilder _logEntries = new StringBuilder();
		static void LogBegin()
		{
#if DEBUG
			_logEntries = new StringBuilder();
#endif
		}
		/// <summary>
		/// Outputs a line of text to the trace log.
		/// </summary>
		/// <param name="p"></param>
		static public void Log(string p)
		{
#if DEBUG
			//StringWriter sw = new StringWriter();
			//XmlWriter xw = new XmlTextWriter(sw);
			//xw.WriteStartDocument();
			_logEntries.AppendFormat("{1}{0} (ticks)\r\n", DateTime.Now.Ticks, p.PadRight(60));
			//_logEntries.AppendFormat("{1}{0:ss.ffffff} (ss.ffffff)\r\n", DateTime.Now.TimeOfDay, p.PadRight(50));
#endif
		}
		static void LogEnd()
		{
#if DEBUG
			for (int numTries = 0; numTries < 10; ++numTries)
			{
				try
				{
					File.WriteAllText(Environment.GetEnvironmentVariable("TEMP") + @"\TurboLog.txt", _logEntries.ToString());
					break;
				}
				catch
				{
					Thread.Sleep(100);
				}
			}
#endif
		}
#endif
		public static string DoResolveUrl(string url)
		{
			if (string.IsNullOrEmpty(url)) return "";
			if (TPage.Current != null)
				return TPage.Current.ResolveUrl(url);

			// TODO: implement some code to resolve URL in design mode

			return url;
		}
		#endregion
		#endregion
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public TPage()
		{
			_globalControls = new ControlCollection<GlobalControlReference>(this._specialContainer);
			_controlReferenceGroups = new ControlCollection<ControlReferenceGroup>(this._specialContainer);
			_scenarios = new ScenarioCollection(this._specialContainer);
		}
		#endregion
		#region METHODS
		/// <summary>
		/// This method is called when a Link tries using the HrefJS for Href by automatically converting the hashed HrefJS into a valid URL.
		/// </summary>
		/// <returns></returns>
		public virtual string GetReplacementForHash()
		{
			return this.ResolveUrl(this.Request.Path) + "?";
		}
		/// <summary>
		/// Searches the page naming container for a server control with the specified identifier.
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public override Control FindControl(string id)
		{
			TControl bc;
			if (this._controls.TryGetValue(id, out bc))
				return bc;
			return base.FindControl(id);
		}
		#endregion
		#endregion
	}
}